package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strings"

	"github.com/skip2/go-qrcode"
	"github.com/tadvi/winc"
)

func main() {

	//1.获取所有当前局域网络的ip，并存入ips数组
	ifaces, err := net.Interfaces()
	if err != nil {
		fmt.Println(err)
		return
	}
	ips := make([]string, 0)
	for _, i := range ifaces {
		// 跳过虚拟接口和非活动接口
		if i.Flags&net.FlagUp == 0 || i.Flags&net.FlagLoopback != 0 {
			continue
		}
		addrs, err := i.Addrs()
		if err != nil {
			fmt.Println(err)
			continue
		}
		for _, addr := range addrs {
			switch v := addr.(type) {
			case *net.IPNet:
				if !v.IP.IsLoopback() && v.IP.To4() != nil {
					// fmt.Println(v.IP.String())
					ips = append(ips, v.IP.String())
				}
			case *net.IPAddr:
				if !v.IP.IsLoopback() && v.IP.To4() != nil {
					// fmt.Println(v.IP.String())
					ips = append(ips, v.IP.String())
				}
			}
		}
	}

	//2.从获取到的ips数组中，找到有可能的是局域网成员的ip
	ip := ips[0]
	for _, str := range ips {
		if !strings.HasSuffix(str, ".1") {
			ip = str
			break
		}
	}

	//3.开启静态文件服务
	go func() {
		fs := http.FileServer(http.Dir("./"))
		http.Handle("/", http.StripPrefix("/", fs))
		log.Fatal(http.ListenAndServe(":80", nil))
	}()

	//4.创建窗口
	mainWindow := winc.NewForm(nil)
	mainWindow.SetSize(288, 266) // (width, height)
	mainWindow.SetText("文件服务器")
	mainWindow.Center()
	mainWindow.OnClose().Bind(wndOnClose)

	lable := winc.NewLabel(mainWindow)
	lable.SetSize(1000, 20)
	lable.SetPos(8, 8)
	_dir, _ := os.Getwd()
	lable.SetText("当前目录： " + _dir)

	lable2 := winc.NewLabel(mainWindow)
	lable2.SetSize(1000, 20)
	lable2.SetPos(8, 28)
	lable2.SetText("当前网络ip： " + ip)

	img := winc.NewImageView(mainWindow)
	img.SetPos(54, 48)

	//4.1.窗口菜单
	menu := mainWindow.NewMenu()
	modelMenu := menu.AddSubMenu("切换网络")
	for _, str := range ips {
		menuItem := modelMenu.AddItemRadio(str, winc.NoShortcut)
		menuItem.OnClick().Bind(func(e *winc.Event) {
			lable2.SetText("当前网络ip： " + str)
			showImg(str, img)
			menuItem.SetChecked(true)
		})
		if str == ip {
			menuItem.SetChecked(true)
		}
	}

	showImg(ip, img)

	menu.Show()
	mainWindow.Show()
	winc.RunMainLoop()
}

func wndOnClose(arg *winc.Event) {
	winc.Exit()
}

func showImg(str string, imageView *winc.ImageView) {
	filePath := "qr.png"
	_url := "http://" + str
	qrcode.WriteFile(_url, qrcode.Low, 160, filePath)
	imageView.Hide()
	imageView.DrawImageFile(filePath)
	imageView.Show()
	os.Remove(filePath)
}
